#include "qtab_ui_logic.h"
#include <QDebug>

QTabUiLogic::QTabUiLogic(QTabUi *ui, EventGridWidget *gridWidget, QObject *parent)
    : QObject(parent), ui(ui), m_tabWidget(ui->getTabWidget()), gridWidget(gridWidget)
{
    m_tabWidget = ui->getTabWidget();
    connect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabCurrentChanged(int)));
    connect(m_tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(onTabCloseRequested(int)));
    connect(ui->searchButton,
            &QPushButton::clicked,
            this,
            &QTabUiLogic::onSearchButtonClicked_Manga);
    connect(ui->searchButton2,
            &QPushButton::clicked,
            this,
            &QTabUiLogic::onSearchButtonClicked_ZhouBian);
    MangaProductList();
    ZhouBianProductList();
}

QTabWidget *QTabUiLogic::getTabWidget()
{
    return m_tabWidget; // 返回 QTabWidget 指针
}

void QTabUiLogic::onTabCurrentChanged(int index)
{
    qDebug() << "Page changed to: " << index;
}

void QTabUiLogic::onTabCloseRequested(int index)
{
    m_tabWidget->removeTab(index);
}

void QTabUiLogic::onSearchButtonClicked_Manga()
{
    QString searchText = ui->lineEdit->text();  // Use the member variable lineEdit
    PptpMessage requestMessage;
    QJsonObject parameters;

    // Retrieve selected region filter from QComboBox
    QString selectedRegion = ui->cityComboBox->currentText();
    if (selectedRegion != "全国")  // Only filter if a specific city is selected
    {
        parameters["filterCriteria"] = selectedRegion;
    }

    // Add search text if provided
    if (!searchText.isEmpty())
    {
        parameters["productName"] = searchText;
    }

    // Retrieve selected sort option from QComboBox
    QString sortBy = ui->filterComboBox->currentText();
    if (!sortBy.isEmpty() && sortBy != "无排序") // Exclude "无排序" from parameters
    {
        parameters["sortBy"] = sortBy;
    }

    // Set product type
    parameters["productType"] = "展会演出";

    // Set up the request message
    requestMessage.setParameters(parameters);
    qDebug() << parameters;

    // Specify the API path and initiate the request
    requestMessage.setPath("product/getProducts");
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &QTabUiLogic::onMangaProductListResponse);
}


void QTabUiLogic::onSearchButtonClicked_ZhouBian()
{
    // Get search text from lineEdit2
    QString searchText = ui->lineEdit2->text();
    qDebug() << "搜索内容:" << searchText;

    PptpMessage requestMessage;
    QJsonObject parameters;

    // Get selected product type from categoryComboBox
    QString selectedCategory = ui->categoryComboBox->currentText();
    if (selectedCategory != "全部分类") // Assuming "全部分类" means no specific filter
    {
        parameters["filterCriteria"] = selectedCategory;
    }

    // Add product name (optional)
    if (!searchText.isEmpty())
    {
        parameters["productName"] = searchText;
    }

    // Get selected sorting option from sortComboBox
    QString sortBy = ui->sortComboBox->currentText();
    if (!sortBy.isEmpty() && sortBy != "无排序") // Exclude "无排序" from parameters
    {
        parameters["sortBy"] = sortBy;
    }

    // Add product type as a fixed parameter
    parameters["productType"] = "霹雳周边";
    requestMessage.setParameters(parameters);

    // Set request path
    requestMessage.setPath("product/getProducts");

    // Print parameters for debugging
    qDebug() << "Request Parameters:" << parameters;

    // Send request
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &QTabUiLogic::onZhoubianProductListResponse);
}
void QTabUiLogic::MangaProductList()
{
    // 准备请求消息
    PptpMessage requestMessage;
    QJsonObject parameters;
    parameters["productType"] = "展会演出";
    requestMessage.clear();
    requestMessage.setParameters(parameters);
    requestMessage.setPath("product/getProducts");
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &QTabUiLogic::onMangaProductListResponse);
}
void QTabUiLogic::onMangaProductListResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    QJsonArray productListArray = responseParameters.value("productList").toArray();
    qDebug() <<"漫展获取值"<< responseParameters;
    QHash<QString, QByteArray> files = responseMessage.getFiles();
    mangaProductList.clear();
    for (int i = 0; i < productListArray.size(); ++i)
    {
        QJsonObject productObject = productListArray[i].toObject();
        Product product;
        product.productId = productObject.value("productId").toInt();
        product.productName = productObject.value("productName").toString();
        product.price = productObject.value("price").toDouble();
        product.stock = productObject.value("stock").toInt();
        product.sales = productObject.value("sales").toInt();
        product.date = productObject.value("date").toString();
        product.description = productObject.value("description").toString();
        QString filename = QString::number(product.productId);
        QByteArray imageData = files.value(filename);
        QPixmap productImage;
        productImage.loadFromData(imageData);
        product.productImage = productImage;
        mangaProductList.append(product);
    }
    displayMangaProductList();
}
void QTabUiLogic::displayMangaProductList()
{
    gridWidget->populateEventWidgets();
    for (int i = 0; i < mangaProductList.size(); ++i)
    {
        const Product &product = mangaProductList[i];
        // 商品数据
        QPixmap image = product.productImage.isNull() ? QPixmap(":/icon/default_product.png")
                                                      : product.productImage;
        QString theme = product.productName;
        QDate date = QDate::fromString(product.date, "yyyy-MM-dd");
        qDebug() << "转换的日期" << date;
        QString location = "库存：" + QString::number(product.stock) + " 销量：" + QString::number(product.sales);
        QString price = "￥" + QString::number(product.price);
        QString description = product.description; // Retrieve the description
         gridWidget->setEventData(image, theme, date, location, price, description, product.productId, i); // Pass the description
    }
}

void QTabUiLogic::ZhouBianProductList()
{
    PptpMessage requestMessage;
    QJsonObject parameters;
    parameters["productType"] = "霹雳周边";
    requestMessage.clear();
    requestMessage.setParameters(parameters);
    requestMessage.setPath("product/getProducts");
    pptpclient.pptpConnect(IP,
                           PORT,
                           requestMessage,
                           this,
                           &QTabUiLogic::onZhoubianProductListResponse);
}
void QTabUiLogic::onZhoubianProductListResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug() << responseParameters;
    QJsonArray productListArray = responseParameters.value("productList").toArray();
    QHash<QString, QByteArray> files = responseMessage.getFiles();
    zhoubianProductList.clear();
    for (int i = 0; i < productListArray.size(); ++i)
    {
        QJsonObject productObject = productListArray[i].toObject();
        Product product;
        qDebug() << "商品id" << productObject.value("productId").toInt();
        product.productId = productObject.value("productId").toInt();
        product.productName = productObject.value("productName").toString();
        product.price = productObject.value("price").toDouble();
        product.stock = productObject.value("stock").toInt();
        product.sales = productObject.value("sales").toInt();
        product.date = productObject.value("date").toString();
        product.description = productObject.value("description").toString();
        QString filename = QString::number(product.productId);
        QByteArray imageData = files.value(filename);
        QPixmap productImage;
        productImage.loadFromData(imageData);
        product.productImage = productImage;
        zhoubianProductList.append(product);
    }
    displayzhoubianProductList();
}
void QTabUiLogic::displayzhoubianProductList()
{
    gridWidget2->populateProductWidgets();
    for (int i = 0; i < zhoubianProductList.size(); ++i)
    {
        const Product &product = zhoubianProductList[i];

        // 商品数据
        QPixmap image = product.productImage.isNull() ? QPixmap(":/icon/default_product.png")
                                                      : product.productImage;
        QString theme = product.productName;
        QDate date = QDate::fromString(product.date, "yyyy-MM-dd");
        QString location = "库存：" + QString::number(product.stock) + " 销量：" + QString::number(product.sales);
        QString price = "￥" + QString::number(product.price);
         QString description = product.description; // Retrieve the description
        // 设置到UI组件中
        gridWidget2->setEventData(image, theme, price, description,product.productId, i);
    }
}
QTabUiLogic::~QTabUiLogic() {}
